package com.spit.hkpost

import android.bld.ScanManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.view.KeyEvent
import androidx.activity.viewModels
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.LanguageUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.spit.hkpost.base.BaseActivity
import com.spit.hkpost.bean.RfidStateBean
import com.spit.hkpost.databinding.AMainBinding
import com.spit.hkpost.ext.SCAN_STATUS_SCAN
import com.spit.hkpost.util.CacheUtil
import com.spit.hkpost.viewmodel.AssetModel
import com.spit.hkpost.viewmodel.AssetSearchmModel
import com.spit.hkpost.viewmodel.RfidModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.Locale

class MainActivity : BaseActivity<RfidModel, AMainBinding>() {

    private val assetModel: AssetModel by viewModels()

    private val rfidModel: RfidModel by viewModels()

    private val assetSearchmModel: AssetSearchmModel by viewModels()

    var scanManager: ScanManager? = null

    override fun initView(savedInstanceState: Bundle?) {
        BarUtils.setStatusBarLightMode(this, true)
        BarUtils.setStatusBarColor(this, getColor(R.color.w_f4f9fd))

        try {
            //扫描头功能
            scanManager = ScanManager.getDefaultInstance(this)
            // 0广播
            scanManager!!.opMode = 0
            //震动
//        scanManager!!.vibrate = false
//        scanManager!!.handleKey = true
            scanManager!!.playSound = false
            // 打开扫描
            val openScanner = scanManager!!.openScanner()
            if (!openScanner){
                ToastUtils.showShort("啓動掃描失敗，請重新打開APP")
                LogUtils.e("启动扫描失败")
            }
            //
            val filter = IntentFilter()
            filter.addAction("scan.rcv.message")
            registerReceiver(mScanReceiver, filter)
        }catch (e: Exception){
            ToastUtils.showShort("啓動掃描失敗，請重新打開APP")
        }

        lifecycle.addObserver(object : DefaultLifecycleObserver {
            override fun onPause(owner: LifecycleOwner) {
                super.onPause(owner)
                mViewModel.isOpen.value = false
            }

            override fun onStop(owner: LifecycleOwner) {
                super.onStop(owner)
                if (!AppUtils.isAppForeground()) {
                    //app 进入后台
//                    mViewModel.isActive.set(false) //记录当前已经进入后台
                    mViewModel.isOpen.value = false
                }
            }

            override fun onResume(owner: LifecycleOwner) {
                super.onResume(owner)

            }

            override fun onDestroy(owner: LifecycleOwner) {
                super.onDestroy(owner)
                scanManager!!.closeScanner()
                unregisterReceiver(mScanReceiver)
            }

        })

        if (CacheUtil.isFirst()){
            CacheUtil.setFirst(false)
            val displayName = LanguageUtils.getSystemLanguage().displayName
            if (displayName.contains("繁體")){
                CacheUtil.setLanguage(1)
            }else if (displayName.contains("中文")){
                CacheUtil.setLanguage(0)
            }else{
                CacheUtil.setLanguage(2)
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        // rfid数据接收回调
        mViewModel.rfidData.observe(this, {
            var tagId = mViewModel.rfidData.value!!.TagId
            if (tagId.contains(" ")) {
                tagId = tagId.replace(" ", "")
            }
            LogUtils.e(tagId, it.Rssi)
            //搜索/识别回调
            if (mViewModel.tagFindParam == null) {
                assetModel.epcData.value = RfidStateBean(
                    tagId = tagId,
                    scanStatus = SCAN_STATUS_SCAN,
                    rssi = it.Rssi
                )
            } else {
                assetSearchmModel.epcData.value = RfidStateBean(
                    tagId = tagId,
                    rssi = it.Rssi
                )
            }
        })

        //是否启动rdif
        mViewModel.isOpen.observe(this@MainActivity, { resultState ->
            mViewModel.viewModelScope.launch(Dispatchers.IO) {
                //啓動才接串口
                /*if (resultState && mViewModel.initConn.get()) {
                    mViewModel.isScan.set(true)
                    mViewModel.onStart(mViewModel.tagFindParam)
                }else{
                    if (mViewModel.isScan.get()) {
                        mViewModel.isScan.set(false)
                        mViewModel.onClose()
                    }
                }*/
                //打開APP就接入串口
                if (resultState){
                    mViewModel.config()
                    mViewModel.isScan.set(true)
                    mViewModel.onStart(mViewModel.tagFindParam)
                }else{
                    if (mViewModel.isScan.get()) {
                        mViewModel.isScan.set(false)
                        mViewModel.onClose()
                    }
                }
            }
        })

        //指定搜索RFID
        mViewModel.isSearchOpen.observe(this, {
            if (com.blankj.utilcode.util.StringUtils.isEmpty(it)) {
                mViewModel.tagFindParam = null
                mViewModel.isOpen.value = false
            } else {
                mViewModel.tagFindParam = it
                mViewModel.isOpen.value = true
            }
        })

        mViewModel.language.observe(this, {languageSelected->
            if (languageSelected < 0)return@observe
            when (languageSelected) {
                0 -> {
                    LanguageUtils.applyLanguage(Locale.SIMPLIFIED_CHINESE)
                }
                1 -> {
                    LanguageUtils.applyLanguage(Locale.TRADITIONAL_CHINESE)
                }
                2 -> {
                    LanguageUtils.applyLanguage(Locale.ENGLISH)
                }
            }
            CacheUtil.setLanguage(languageSelected)
        })

    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == 619){
            val openScanner = scanManager!!.openScanner()
            if (!openScanner){
                scanManager!!.openScanner()
            }
            // 开始扫描
            val startDecode = scanManager!!.startDecode()
            if (!startDecode){
                LogUtils.e("扫描失败")
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    private val mScanReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val barocode = intent.getByteArrayExtra("barocode")
            val barocodelen = intent.getIntExtra("length", 0)
            val temp = intent.getByteExtra("barcodeType", 0.toByte())
            val aimid = intent.getByteArrayExtra("aimid")
            var barcodeStr = String(barocode!!, 0, barocodelen)
            assetModel.epcData.value = RfidStateBean(
                tagId = barcodeStr,
                scanStatus = SCAN_STATUS_SCAN,
                rssi = "0.00"
            )
        }
    }

}